<script setup>
import {computed, reactive, ref} from 'vue'

const count = ref(0)
const inc = () => {
  count.value++
}
const dec = () => {
  count.value--
}
const reset = () => {
  count.value = 0
}
// 使用computed计算总金额
const balance = computed(() => {
  if (count.value > 0) {
    return count.value * 100
  } else if (count.value < 0) {
    return count.value * -100
  } else {
    return 0
  }
})
const shoppingCarts = reactive([
  {
    name: 'K80-Champion',
    price: 3999,
    amount: 1,
  },
  {
    name: 'Watch5-eSMI',
    price: 799,
    amount: 1,
  },
  {
    name: 'fridge',
    price: 1999,
    amount: 1,
  },
  {
    name: 'Computer',
    price: 10999,
    amount: 2,
  },
])
const getConsume = computed(() => {
  let sum = 0
  for (const item of shoppingCarts) {
    sum += item.price * item.amount
  }
  return sum
})
</script>
<template>
  <div>
    <div>count: {{ count }}</div>
    <button @click="inc">+</button>
    <button @click="dec">-</button>
    <button @click="reset">reset</button>
    <div>balance: {{ balance }}</div>
    <hr/>
    <table border="1" cellpadding="0" cellspacing="0" style="text-align: center; margin: 0 auto;">
      <tr>
        <th>序号</th>
        <th>name</th>
        <th>price</th>
        <th>amount</th>
      </tr>
      <tr v-for="(item, index) in shoppingCarts" :key="index">
        <td>{{ index + 1 }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>{{ item.amount }}</td>

      </tr>
      <p style="text-align: right">消费总额：{{ getConsume }}</p>

    </table>
  </div>

</template>
<style scoped>
th,td{width: 100px;}
td{text-align: center;}
</style>